1

I have design a canvas now I want to call a image in that canvas. I have gone through the tutorials but I don't know how to implement that. My image is high resolution but I want to reduce that image size and resolution with javascript. Anybody will help me.

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

<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();

ctx.moveTo(8,200);
ctx.lineTo(8,308);
ctx.moveTo(259,76);
ctx.lineTo(259,308);
ctx.moveTo(259,308);
ctx.lineTo(8,308);
ctx.moveTo(8,200);
ctx.lineTo(259,76);
ctx.stroke();
var imageObj = new Image();

  imageObj.onload = function() {
    ctx.drawImage(imageObj, 69, 50);
  };
  imageObj.src = 'img/logo.jpg', height='42', width='42';
</script>

I am not able to call image. Anybody will help me how to convert this javascript in jquery?

Thanks

Vaibhav Dass
  • 324
  • 1
  • 4
  • 15

1 Answers1

1

You need to use the following syntax if you want to resize the image too.

context.drawImage(img,x-Position,y-Position,width,height);

Here is an Updated JSFiddle as an example.

You can read more about drawImage function in this W3CSchool's article.

Shiva
  • 6,677
  • 4
  • 36
  • 61
  • Hi Shiva, you have solved my problem, but now the issue is I am not able to use canvas as a picture frame I change this line "ctx.drawImage(imageObj,100, 160, 100, 100);" to "ctx.drawImage(imageObj,9, 58, 250, 250);" now how do I remove the outer part of the image from the canvas border? will you help me? – Vaibhav Dass Jun 19 '14 at 07:02
  • @VaibhavDass: vaibhav please refer to this post, probably its what yoy are trying to achieve. http://stackoverflow.com/questions/18988118/how-can-i-clip-inside-a-shape-in-html5-canvas In it do see the Jsfiddle in 'GameAlchemist''s answer – Shiva Jun 19 '14 at 07:25