Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue canvas

作者:紛手也是一茽の媄丽   发布日期:2026-03-16   浏览:90

// Vue + Canvas 示例代码

<template>
  <div>
    <canvas ref="myCanvas" width="500" height="500"></canvas>
  </div>
</template>

<script>
export default {
  mounted() {
    this.drawCanvas();
  },
  methods: {
    drawCanvas() {
      const canvas = this.$refs.myCanvas;
      const ctx = canvas.getContext('2d');

      // 绘制一个简单的矩形
      ctx.fillStyle = 'green';
      ctx.fillRect(50, 50, 150, 100);

      // 绘制一个圆形
      ctx.beginPath();
      ctx.arc(300, 150, 50, 0, Math.PI * 2);
      ctx.fillStyle = 'blue';
      ctx.fill();
      ctx.closePath();

      // 绘制一条线
      ctx.beginPath();
      ctx.moveTo(50, 250);
      ctx.lineTo(450, 250);
      ctx.strokeStyle = 'red';
      ctx.lineWidth = 5;
      ctx.stroke();
    }
  }
};
</script>

<style scoped>
canvas {
  border: 1px solid black;
}
</style>

解释说明:

  • 模板部分 (<template>):包含一个 <canvas> 元素,并通过 ref 属性将其引用传递给 Vue 实例,以便在 JavaScript 中操作它。
  • 脚本部分 (<script>)
    • mounted() 生命周期钩子:当组件挂载后调用 drawCanvas 方法。
    • drawCanvas() 方法:获取 canvas 上下文并绘制图形。包括绘制矩形、圆形和线条。
  • 样式部分 (<style scoped>):为 canvas 添加边框,使其更易于查看。

这个示例展示了如何在 Vue 中使用原生的 HTML5 Canvas API 来绘制图形。

上一篇:bootstrapvue

下一篇:vue 甘特图

大家都在看

vue.js devtools用法

three.js vue

vue js for循环

vue.min.js 本地引入

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3 写法

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站