生命周期
canvas应该在mounted的生命周期中初始化,在updated中是无效的。
export default {
mounted() {
this.initCanvas()
},
methods: {
initCanvas() {
console.log("初始化canvas")
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
}
}
}
响应式画布
当需要使canvas铺满全屏时,直接使用css声明的效果不是我们需要的效果。
// 错误的效果,将造成图像变形拉伸
.canvas {
width: 100vw;
height: 100vh;
}
正确的做法,我们应该给canvas的宽高赋值:
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
let winW = window.innerWidth
let winH = window.innerHeight
canvas.width = winW
canvas.height = winH
响应式画布:
let canvas;
let ctx;
export default {
mounted() {
this.initCanvas()
// 当调整窗口大小时重绘canvas
window.onresize = () => {
this.initCanvas()
}
},
methods: {
initCanvas() {
console.log("初始化canvas")
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth
canvas.height = window.innerHeight
this.drawSmile()
},
drawSmile() {
ctx.beginPath();
ctx.arc(75, 75, 50, 0, Math.PI * 2, true); // 绘制
ctx.moveTo(110, 75);
ctx.arc(75, 75, 35, 0, Math.PI, false); // 口(顺时针)
ctx.moveTo(65, 65);
ctx.arc(60, 65, 5, 0, Math.PI * 2, true); // 左眼
ctx.moveTo(95, 65);
ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // 右眼
ctx.stroke();
}
}
}
摘自:https://www.cnblogs.com/unclefang/p/11180337.html
https://blog.csdn.net/weixin_42152696/article/details/103053003
下载canvas图片
var canvas = document.getElementById("pdf-64");
var img = canvas.toDataURL("image/png");
var url = img; // 获取图片地址
var a = document.createElement('a'); // 创建一个a节点插入的document
var event = new MouseEvent('click') ; // 模拟鼠标click点击事件
a.download = 'beautifulGirl' // 设置a节点的download属性值
a.href = url; // 将图片的src赋值给a节点的href
a.dispatchEvent(event);
网友评论