vue项目中使用canvas
约 376 字大约 1 分钟
2025-08-01
在 html 中使用 canvas
<!DOCTYPE html>
<html>
<body>
<img
id="scream"
width="224"
height="162"
src="/i/eg_flower.png"
alt="The Scream"
/>
<p>Canvas:</p>
<canvas
id="myCanvas"
width="244"
height="182"
style="border:1px solid #d3d3d3;"
>
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
window.onload = function () {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 10, 10);
};
</script>
</body>
</html>
效果如下:
在 vue 中使用 canvas
<template>
<div id="app">
<p>vue项目中测试canvas</p>
<canvas id="mycanvas" ref="mycanvas"></canvas>
<img id="myimg" ref="myimg" src="./assets/logo.png" />
</div>
</template>
<script>
export default {
name: "app",
mounted() {
this.draw();
},
methods: {
draw() {
window.onload = function () {
var img = document.getElementById("myimg");
var c = document.getElementById("mycanvas");
var cxt = c.getContext("2d");
cxt.drawImage(img, 0, 0, 80, 80);
};
},
},
};
</script>
<style>
#app {
text-align: center;
}
canvas {
background-color: lightsalmon;
}
img {
width: 50px;
height: 50px;
}
</style>
易错点
1、在找到 canvas
和 img
元素的时候,用 document.getElementById("mycanvas");
可以找到,但用 var ctx = this.$refs.mycanvas;
将会找不到,会报 undefined
错误。
draw() {
window.onload = function() {
var c = this.$refs.mycanvas;
var img = this.$refs.myimg;
var cxt = c.getContext("2d");
cxt.drawImage(img, 0, 0, 80, 80)
};
}
2、不加window.onload不会绘制图片,因为 drawImage()
图片没加载完的情况下使用不被调用,绘制就会失败。具体解决办法见 canvas - drawImage()方法绘制图片不显示的问题