canvas/pages/index/index.vue
2025-05-08 11:17:46 +08:00

53 lines
1.6 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<view>
<!-- 定义canvas画布 // 设置canvas大小为200x200像素 -->
<canvas canvas-id="canvas" id="canvas" style="width: 200px; height: 200px;border: 1px solid red;" :width="canvasWidth" :height="canvasHeight"></canvas>
<!-- 添加一个按钮用于触发绘图 -->
<button @click="handleDraw">点击绘制圆形</button>
</view>
</template>
<script setup>
import { ref, onMounted } from 'vue'
const canvasWidth = ref(200) // 动态设置Canvas宽度
const canvasHeight = ref(200) // 动态设置Canvas高度
// 定义绘图函数
function draw() {
const ctx = uni.createCanvasContext('canvas') // 创建canvas绘图上下文
// 绘制外圆
ctx.beginPath() // 开始路径
ctx.arc(100, 100, 80, 0, Math.PI * 2) // 在坐标(100, 100)处绘制半径为80的圆形
ctx.setFillStyle('rgba(0, 0, 0, 1)') // 设置填充颜色为黑色,无透明度
ctx.fill() // 填充所创建的路径
// 绘制内圆以形成环形效果
ctx.beginPath() // 开始新的路径
ctx.arc(100, 100, 75, 0, Math.PI * 2) // 在相同中心点(100, 100)但半径为60的圆形
ctx.setFillStyle('white') // 设置填充颜色为白色
ctx.fill() // 填充以“清除”内部区域,形成环形
ctx.draw(false, setTimeout(()=>{
console.log(3)
},300))
// ctx.draw(true) // 将上述所有操作提交到canvas进行渲染
}
// 按钮点击事件处理函数
const handleDraw = () => {
console.log('111111');
draw(); // 调用绘图函数
console.log('222222222');
}
onMounted(() => {
// 确保在组件挂载后可以获取到Canvas元素
})
</script>
<style scoped>
button {
margin-top: 10px;
}
</style>