let img=new Image(); if(img.complete) { console.log('dd'); }
img.src="http://localhost:8888/static/img/logo11.6d2b322.png"
img.onload = function() {
console.log('ff')
}
首先,一张图片在定义 img.src="http://localhost:8888/static/img/logo11.6d2b322.png"的时候,img就已经结束了它的渲染,那么自然而然不会进到下面的onload的函数。
好的,现在把图片往下调就可以
let img=new Image(); if(img.complete) { console.log('dd'); } img.onload = function() { console.log('ff') }
img.src="http://localhost:8888/static/img/logo11.6d2b322.png"
那么一次完整的vue+canvas绘制图片的过程就如下所示:
let cans=document.getElementById("myCanvas"); let ctx=cans.getContext("2d"); let img=new Image(); img.onload = function(){ ctx.drawImage(img,50,50,100,100); ctx.strokeStyle = "#0695FF"; //定义矩形的颜色 ctx.strokeRect(50,50,100,100); ctx.strokeRect(50,170,100,100); }; img.src="http://localhost:8888/static/img/logo11.6d2b322.png" ctx.drawImage(img, 10, 10);
但是这个毕竟还是太扑街了,最后成功的demo如下
<template> <div> <h2> TestCanvas </h2> <img v-show="false" ref="myImg" src="../assets/logo.png" > <canvas ref="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;" > 您的浏览器不支持 HTML5 canvas 标签。 </canvas> <button @click="downloadCanvas"> 下载 </button> </div> </template> <script> export default { name: "TestCanvas" , data () { return { } } , methods: { alert : function () { alert("emem") ; } , downloadCanvas : function () { // 内部函数1(可忽略细节) const saveFile = function(data, fileName){ let save_link = document.createElement('a'); save_link.href = data; save_link.download = fileName; let event = document.createEvent('MouseEvents'); event.initEvent("click", true, false); save_link.dispatchEvent(event); }; // 内部函数2(可忽略细节) const imgType = function (ty) { let type = ty.toLowerCase().replace(/jpg/i, 'jpeg'); var r = type.match(/png|jpeg|bmp|gif/)[0]; return 'image/' + r; } ; const type = 'png'; //设置下载图片的格式 const cans = this.$refs.myCanvas ; //canvas实例子 const img_png_src = cans.toDataURL("image/png"); //将canvas保存为图片 const imgData = img_png_src.replace(imgType(type),'image/octet-stream'); const filename = 'canvas' + '.' + type; //下载图片的文件名 // shoot saveFile(imgData,filename); } } , mounted: function () { console.log("挂载成功") ; var c=this.$refs.myCanvas ; var ctx=c.getContext("2d"); var img=this.$refs.myImg; // 贴图 ctx.drawImage(img,0,0); ctx.font="10px Arial"; // 打水印 ctx.fillText("Kingdee",160,90); } } </script>