DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert Excel and CSV Documents to HTML in Java
  • How to Convert DOCX to HTML in Java
  • How to Convert HTML to PDF in Java
  • Creating Scrolling Text With HTML, CSS, and JavaScript

Trending

  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Understanding and Mitigating IP Spoofing Attacks
  • Using Python Libraries in Java
  • Customer 360: Fraud Detection in Fintech With PySpark and ML
  1. DZone
  2. Coding
  3. Languages
  4. Convert Any Image to HTML5 Canvas

Convert Any Image to HTML5 Canvas

By 
Hemanth HM user avatar
Hemanth HM
·
Aug. 27, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
21.0K Views

Join the DZone community and get the full member experience.

Join For Free

Even before talking about the technicalities of converting an image to a canvas element, check out the demo!

DEMO input any image URL there and hit the convert button!

P.S : It also accepts data-uri!

The code :

function draw() {
        // Get the canvas element and set the dimensions. 
        var canvas = document.getElementById('canvas');
        canvas.height = window.innerHeight;
        canvas.width = window.innerWidth;
 
       // Get a 2D context.
        var ctx = canvas.getContext('2d');
 
        // create new image object to use as pattern
        var img = new Image();
        img.src = document.getElementById('url').value;
        img.onload = function(){
            // Create pattern and don't repeat! 
           var ptrn = ctx.createPattern(img,'no-repeat');
           ctx.fillStyle = ptrn;
           ctx.fillRect(0,0,canvas.width,canvas.height);
 
        }
 }

The Magic Behind :

All the credits goes to createPattern()

nsIDOMCanvasPattern createPattern(in nsIDOMHTMLElement image, in DOMString repetition);

Elobrating :

context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

Hope this was useful, anyway there are loads of fun with the canvas element, happy hacking!

Edit 0

After the interesting question by @pinkham in the comment section, from the page of MDN :

Although you can use images without CORS approval in your canvas, doing so taints the canvas. Provided that you have a server hosting images along with appropriate Access-Control-Allow-Origin header, you will be able to save those images to localStorage as if they were served from your domain.

 

 var img = new Image,
    canvas = document.createElement("canvas"),
    ctx = canvas.getContext("2d"),
    src = "http://example.com/image"; // insert image url here
 
   img.crossOrigin = "Anonymous";
 
    img.onload = function() {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage( img, 0, 0 );
     localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );
   }
 
   img.src = src;
   // make sure the load event fires for cached images too
   if ( img.complete || img.complete === undefined ) {
      img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      img.src = src;
  }
HTML Convert (command)

Published at DZone with permission of Hemanth HM, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert Excel and CSV Documents to HTML in Java
  • How to Convert DOCX to HTML in Java
  • How to Convert HTML to PDF in Java
  • Creating Scrolling Text With HTML, CSS, and JavaScript

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!