简体   繁体   English

如何使用JS加载本地图像?

[英]How do I load a local image using JS?

I want to load two separate images in my script. 我想在脚本中加载两个单独的图像。 I've accomplished it using: 我已经完成了使用:

<img src="iphone4.png" id="img1">
<img src="screenshot.png" id="img2">

<script>
        window.onload = function () {
            var img1 = document.getElementById('img1');
            var img2 = document.getElementById('img2');
</script>

Problem here though is that the images should not be visible on the page but are when loaded using markup. 但是,这里的问题是图像在页面上不应该看到,而是在使用标记加载时显示的。 I simply want to load them through the script without first having to add them in the markup. 我只是想通过脚本加载它们,而无需首先在标记中添加它们。 I realize this is an extremely trivial problem, but searching for a solution has given me nothing. 我意识到这是一个非常琐碎的问题,但是寻找解决方案并没有给我任何帮助。

I tried this approach: 我尝试了这种方法:

        window.onload = function () {
            var img1 = "iphone4.png";
            var img2 = "screenshot.png";

But this did not work. 但这没有用。 Can someone with some common JS sense please give me some input on this issue. 可以对JS有一些常识的人可以在这个问题上给我一些建议。

EDIT : So this is how the markup/JS looks now, the images are still displayed and the final merge of the images won't show. 编辑:因此,这就是标记/ JS现在的外观,图像仍显示,并且图像的最终合并不会显示。 The error I get is: 我得到的错误是:

IndexSizeError: Index or size is negative or greater than the allowed amount
[Stanna vid fel]    

var image1 = context.getImageData(0, 0, width, height);

And this is the syntax: 这是语法:

<body>
    <img src="" id="img1">
    <img src="" id="img2">
    <p>Blended image<br><canvas id="canvas"></canvas></p>
    <script>
        window.onload = function () {
            var img1 = document.getElementById('img1');
            var img2 = document.getElementById('img2');

            img1.src = "iphone4.png";
            img2.src = "screenshot.png";

            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            var width = img1.width;
            var height = img1.height;
            canvas.width = width;
            canvas.height = height;

            var pixels = 4 * width * height;
            context.drawImage(img1, 0, 0);
            var image1 = context.getImageData(0, 0, width, height);
            var imageData1 = image1.data;
            context.drawImage(img2, 73, 265);
            var image2 = context.getImageData(0, 0, width, height);
            var imageData2 = image2.data;
            while (pixels--) {
                imageData1[pixels] = imageData1[pixels] * 0 + imageData2[pixels] * 1;
            }
            image1.data = imageData1;
            context.putImageData(image1, 0, 0);
        };
    </script>
window.onload = function () {
        var img1 = new Image();
        var img2 = new Image();

        //EDIT2 you can hide img, or simply not add them to the DOM...
        img1.style.display = "none";
        img2.style.display = "none";

        img1.src = "iphone4.png";
        img2.src = "screenshot.png";

EDIT: DO NOT DO THAT and your images won't be displayed 编辑: 请勿执行此操作,并且不会显示您的图像

        document.body.append(img1);

OR 要么

        document.getElementById("myID").append(img2);

"What I'm doing is merging two images using JS" “我正在做的是使用JS合并两个图像”

Your problem is probably due to the fact that you are trying to draw images that have not been loaded yet. 您的问题可能是由于您试图绘制尚未加载的图像。 To circumvent this issue, you could create the images dynamically and set their src attribute to start loading the image and listen to the image's load event to know when they are fully loaded so that you can perform the merge safely. 为了避免此问题,可以动态创建图像并设置其src属性以开始加载图像,并侦听图像的load事件以了解何时完全加载图像,以便可以安全地执行合并。

I have not tested the code, but it should give you the idea. 我没有测试过代码,但是应该可以给您带来启发。

var images = [
        'iphone4.png',
        'screenshot.png'
    ],
    len = images.length,
    i = 0,
    loadedCount = 0,
    img;

for (; i < len; i++) {
    img = document.createElement('img');

    //listener has to be added before setting the src attribute in case the image is cached
    img.addEventListener('load', imgLoadHandler);

    img.src = images[i];
    images[i] = img;
}

function mergeImages() {
    var img1 = images[0], 
        img2 = images[1];
    //do the merging stuff
}

function imgLoadHandler() {
    if (++loadedCount === len) {
        mergeImages();
    }
}

There is a way with HTML5, but it would still require the user to have dropped the file into a drop target or use a box. HTML5有一种方法,但是仍然需要用户将文件拖放到放置目标或使用框。

Using the File API you can read files, and potentially decode them. 使用File API,您可以读取文件并可能对其进行解码。

Actually reading the file blob and displaying it locally may be tricky though. 实际读取文件blob并在本地显示它可能很棘手。 You may be able to use the FileReader.readAsDataURL method to set the content as a data: URL for the image tag. 您可能可以使用FileReader.readAsDataURL方法将内容设置为数据:图像标签的URL。

example : 例如

$('#f').on('change', function(ev) {
    var f = ev.target.files[0];
    var fr = new FileReader();

fr.onload = function(ev2) {
    console.dir(ev2);
    $('#i').attr('src', ev2.target.result);
};

fr.readAsDataURL(f);
});​

see the working fiddle here : http://jsfiddle.net/alnitak/Qszjg/ 在这里查看工作提琴: http : //jsfiddle.net/alnitak/Qszjg/

You can create an Image without having the actual tag in the markup: 您可以创建Image而无需在标记中包含实际标签:

var img = new Image();
img.src = 'iphone4.png';
//use img however you want

Hope this helps. 希望这可以帮助。

using jquery: 使用jQuery:

$('#my_image').attr('src','image.jpg');

using javasript: 使用javasript:

document.getElementById("my_image").src="image.jpg";

just check path to your image 只需检查图像的路径

Write the below code in head block 将下面的代码写在标题栏中

window.onload = function () { document.getElementById("img1").src="iphone4.png"; window.onload = function(){document.getElementById(“ img1”)。src =“ iphone4.png”; document.getElementById("img2").src="screenshot.png"; document.getElementById(“ img2”)。src =“ screenshot.png”; } }

This will work 这会起作用

Thanks 谢谢

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

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