如何将使用jquery动态创建的img元素加载到HTML5 canvas中

时间:2018-08-15 13:37:26

标签: javascript jquery html5 canvas

我无法在HTML5画布上加载/显示用jquery创建的图像,但是当将图像对象创建为= new Image()时它可以工作

尤其是以以下脚本为例:https://www.html5canvastutorials.com/advanced/html5-canvas-invert-image-colors-tutorial/

但将img源替换为:

imageObj.src = 'https://demo.boundlessgeo.com/geoserver/ows?&service=WMS&request=GetMap&layers=nasa%3Abluemarble&styles=&format=image%2Fjpeg&transparent=false&version=1.1.1&width=256&height=256&srs=EPSG%3A3857&bbox=0,2504688.542848655,2504688.5428486555,5009377.085697314';

并添加属性:imageObj.crossOrigin = "Anonymous";

恰好在var imageObj = new Image();

之后

它允许运行编辑功能,并且图像可以在画布上绘制。

但是,通过使用以下jquery创建图像,该图像不会显示在画布中,并且控制台中不会报告任何错误:

var imageObj = $("<img />",
{ 
crossOrigin: "Anonymous", 
src: "https://demo.boundlessgeo.com/geoserver/ows?&service=WMS&request=GetMap&layers=nasa%3Abluemarble&styles=&format=image%2Fjpeg&transparent=false&version=1.1.1&width=256&height=256&srs=EPSG%3A3857&bbox=0,2504688.542848655,2504688.5428486555,5009377.085697314"  
});

我是否错过了将img绑定到文档的步骤,还是其他内容?

1 个答案:

答案 0 :(得分:0)

为了在示例代码中更改图像创建,您忘记了加载事件。因此,您的代码应为:

var imageObj = $("<img />", {
    crossOrigin: "Anonymous",
    src: "https://demo.boundlessgeo.com/geoserver/ows?&service=WMS&request=GetMap&layers=nasa%3Abluemarble&styles=&format=image%2Fjpeg&transparent=false&version=1.1.1&width=256&height=256&srs=EPSG%3A3857&bbox=0,2504688.542848655,2504688.5428486555,5009377.085697314"
}).on('load', function (e) {
    drawImage(this);
});

var imageObj = $("<img />", {
    crossOrigin: "Anonymous",
    src: "https://demo.boundlessgeo.com/geoserver/ows?&service=WMS&request=GetMap&layers=nasa%3Abluemarble&styles=&format=image%2Fjpeg&transparent=false&version=1.1.1&width=256&height=256&srs=EPSG%3A3857&bbox=0,2504688.542848655,2504688.5428486555,5009377.085697314"
}).on('load', function (e) {
    drawImage(this);
});


function drawImage(imageObj) {
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var x = 69;
    var y = 50;

    context.drawImage(imageObj, x, y);

    var imageData = context.getImageData(x, y, imageObj.width, imageObj.height);
    var data = imageData.data;

    for (var i = 0; i < data.length; i += 4) {
        // red
        data[i] = 255 - data[i];
        // green
        data[i + 1] = 255 - data[i + 1];
        // blue
        data[i + 2] = 255 - data[i + 2];
    }

    // overwrite original image
    context.putImageData(imageData, x, y);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="578" height="400"></canvas>