如何下载图像和画布?

时间:2017-04-17 19:39:37

标签: javascript jquery canvas

我正在尝试绘制画布,也想下载,它与下载和文本工作正常,但我想添加图像也怎么做?下面给出的代码绘制画布并将其下载为png但是如何在画布中添加标题中的图像?

这是html:

<script type="text/javascript">

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

function doCanvas() {
    /* draw something */
    ctx.fillStyle = '#B00000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#fff';
    ctx.font = '60px sans-serif';
    ctx.fillText('Some heading', 10, canvas.height / 2 + 10);
    ctx.fillText('Some Paragraph', 15, canvas.height / 2 + 50);
}


function downloadCanvas(link, canvasId, filename) {
    link.href = document.getElementById(canvasId).toDataURL();
    link.download = filename;
}

document.getElementById('download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

doCanvas();
</script>

这是jQuery:

public function scopeLast($query){
    return $query->orderBy('id', 'DESC')->limit(3);
}

1 个答案:

答案 0 :(得分:0)

 var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');
    **var background = new Image();
background.src = "your image path";**

你必须创建一个变量然后如果你想要画布的背景图像而不是用它

    function doCanvas() {
    ctx.fillRect(0, 0, canvas.width, canvas.height);
**ctx.drawImage(background,400,100,60,90);**
    ctx.fillStyle = '#fff';
    ctx.font = '60px sans-serif';
    ctx.fillText('Some heading', 10, canvas.height / 2 + 10);
    ctx.fillText('Some Paragraph', 15, canvas.height / 2 + 50);
}


function downloadCanvas(link, canvasId, filename) {
    link.href = document.getElementById(canvasId).toDataURL();
    link.download = filename;
}

document.getElementById('download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

doCanvas();
</script>