简体   繁体   English

从本地路径加载图像并在画布上绘制

[英]Load Image from local path and draw it on canvas

I want to draw a image on canvas where the source for image will be set dynamically by user.I am getting following error while trying to set src for image: 我想在画布上绘制一个图像,其中图像的源将由用户动态设置。我在尝试为图像设置src时遇到以下错误:

Not allowed to load local resource: file:///D:/My%20Picsb.jpg' 不允许加载本地资源:file:/// D:/My%20Picsb.jpg'

Is there any way to load file from local drives to draw them on a canvas? 有没有办法从本地驱动器加载文件在画布上绘制它们?

var img = new Image();
img.onload = function () {  
    context.drawImage(img, 20, 20, 50, 50);
};

img.src = "D:\My Pics\tb.jpg";

What you want won't work because of security reasons. 由于安全原因,您想要的东西不起作用。 What you could do, however, is adding a file input field and upload it to the canvas, like this: 但是,你可以做的是添加一个文件输入字段并将其上传到画布,如下所示:

HTML HTML

<input type="file" id="file_input">

JS JS

$("#file_input").change(function(e){


    var URL = window.webkitURL || window.URL;
    var url = URL.createObjectURL(e.target.files[0]);
    var img = new Image();
    img.src = url;


    img.onload = function() {

            img_width = img.width;
            img_height = img.height;

            context.drawImage(img, 0, 0, img_width, img_height);

    }


});

I had the same problem as you not so long ago, and this code did the job when it comes to loading local images onto a canvas. 我不久前遇到了同样的问题,这个代码在将本地图像加载到画布上时起了作用。 I would however also recommend to eventually resize the image, so that it fits into the canvas. 然而,我还建议最终调整图像大小,使其适合画布。 I used the following code (replace 460 with the size of your canvas). 我使用了以下代码(用画布大小替换460 )。

var new_x = 0;
var new_y = 0;

if (img_width > img_height) {
    new_x = 460;
    new_y = (460*img_height)/img_width;
} 

else if (img_height > img_width) {
    new_x = (460*img_width)/img_height;
    new_y = 460;
}

else {
    new_x = 460;
    new_y = 460;
}

context.drawImage(img, 0, 0, new_x, new_y);

I had the need for similar functionality and solved it using ajax by uploading the image temporarily to the server and setting the src attribute of the target img to that temporary file name. 我需要类似的功能,并通过将图像临时上传到服务器并将目标img的src属性设置为该临时文件名来使用ajax解决它。 You can complete the task by creating a cron job that deletes those temporary images from your server's directory. 您可以通过创建从服务器目录中删除这些临时映像的cron作业来完成任务。

No. JavaScript has security block of accessing local files, whether it be reading or writing. 不需要.JavaScript有访问本地文件的安全块,无论是读取还是写入。 Put the file on a webserver ( best on the same domain, because of cross domain issues ). 将文件放在Web服务器上(由于跨域问题,最好在同一个域上)。

Because your user should provide for the file you have to code a file upload solution. 因为您的用户应该提供文件,您必须编写文件上载解决方案。 Reference the internet on how to do that. 参考互联网如何做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM