I am trying to draw a canvas created through javascript on another canvas. But it is not working for me,
Here is my code,
<!DOCTYPE HTML>
<html>
<head>
</script>
<script>
window.onload = function(){
var can1 = document.createElement('canvas');
can1.width = 150;
can1.height = 140;
can1.style.cssText = 'top:2px;left:2px;border:2px solid black;';
var ctx1 = can1.getContext('2d');
var img=new Image();
img.src="images/211.jpg"
ctx1.drawImage(img,0,0);
var can = document.getElementById("c");
var ctx = can.getContext('2d');
ctx.drawImage(can1,0,0);
var canvas = document.getElementById("c");
window.open(canvas.toDataURL());
}
</script>
</head>
<body >
<canvas id="c" style = "position:absolute;top:150px;width:250px;height:350px;left:500px; border:2px solid black;"></canvas>
</body>
</html>
I think the problem was that, when you were trying to drawImage that image into the canvas, image was not ready. so if u do this it works perfectly:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
#myCanvas {
border: 1px solid #9C9898;
}
</style>
<script>
window.onload = function() {
var imageObj = new Image();
imageObj.src = "http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg";
var dynamicCanvas = document.createElement("canvas");
var dynamicContext = dynamicCanvas.getContext("2d");
dynamicCanvas .height="400";
dynamicCanvas.width="578";
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
imageObj.onload = function() {
dynamicContext.drawImage(imageObj, 69, 50);
context=context.drawImage(dynamicCanvas,69,50);
window.open(canvas.toDataURL());
};
};
</script>
</head>
<body>
<canvas id="myCanvas" width="578" height="400"></canvas>
</body>
</html>
and you can adjust the height and width of the dynamic canvas.
if you remove that window.open statement, its perfect.
but there is a problem with canvas.toDataURL()
when you try to do canvas.toDataURL()
for a local file, it gives a security error (if you inspect it through google chrome) i.e.
Uncaught Error: SECURITY_ERR: DOM Exception 18
you can know more about this error : here (see if you are getting this error). anyways, the root cause is sorted out, and there's a new problem now altogether :D..anyways better luck!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With