Nguyễn Thành Nam Nguyễn Thành Nam - 5 months ago 21
Javascript Question

Show canvas image on all id

I have an image URL and I want to show it on 2 canvas



var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");

function draw() {
ctx.drawImage(img,10,10);
}

<p>Image to use:</p>
<img id="scream" onload="draw()" src="http://i.imgur.com/S1juY4A.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>




Answer
  1. Id must be unique, but name can be equal.
  2. If you using canvas inside function onload, you not need to find image element in the dom.
  3. Also i have upgraded your code, now it works with simple resize

    
    function draw(img) {
        var canvases = document.querySelectorAll("canvas[name=myCanvas]");
        for (var i = 0; i < canvases.length; i++) {
          var canvas = canvases[i];
          var factor = Math.min(canvas.height/img.height,  canvas.width/img.width);
          canvas.width = Math.round(img.width* factor);
          canvas.height = Math.round(img.height* factor);
          canvas.getContext("2d").drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);
        }
    }
<p>Image to use:</p>
<img id="scream" onload="draw(this)" src="http://i.imgur.com/S1juY4A.jpg" alt="The Scream">

<p>Canvas:</p>
<canvas name="myCanvas" width="125" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<canvas name="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>