[英]Display Image using canvas in Javascript/Jquery
I have the following code : 我有以下代码:
function createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function() {
document.write('<br><br><br>Image: <img src="'+pastedImage.src+'" height="700" width="700"/>');
}
pastedImage.src = source;
}
Here I am displaying the image through html image tag which I wrote in document.write and provide appropriate height and width to image. 这里我通过html图像标签显示图像,我在document.write中写入并为图像提供适当的高度和宽度。
My question is can it possible to displaying image into the canvas instead of html img tag. 我的问题是可以将图像显示到画布而不是html img标签。 So that I can drag and crop that image as I want.
这样我就可以根据需要拖动和裁剪图像。
But how can I display it in canvas? 但是如何在画布中显示它?
Further I want to implement save that image using PHP but for now let me know about previous issue. 此外,我想使用PHP实现保存该图像,但现在让我知道以前的问题。
Thanks in advance. 提前致谢。
Use CanvasRenderingContext2D.drawImage
. 使用
CanvasRenderingContext2D.drawImage
。
function createImage(source) {
var ctx = document.getElementById('canvas').getContext('2d');
var pastedImage = new Image();
pastedImage.onload = function(){
ctx.drawImage(pastedImage, 0, 0);
};
pastedImage = source;
}
Also MDN seems to be have nice examples . MDN似乎也有很好的例子 。
Try This 尝试这个
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image(); // Create new img element
img.onload = function(){
// execute drawImage statements here This is essential as it waits till image is loaded before drawing it.
ctx.drawImage(img , 0, 0);
};
img.src = 'myImage.png'; // Set source path
Make sure the image is hosted in same domain as your site. 确保图像托管在与您的网站相同的域中。 Read this for Javascript Security Restrictions Same Origin Policy .
阅读本文以了解Javascript安全限制同源策略 。
Eg If your site is http://example.com/ then the Image should be hosted on http://example.com/../myImage.png 例如,如果您的网站是http://example.com/,那么图片应该托管在http://example.com/../myImage.png上
if you try http://facebook.com/..image/ or something then it will throw security error. 如果您尝试http://facebook.com/..image/或其他东西,那么它将引发安全错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.