html正方形裁剪成圆形,HTML5 Canvas 被圆形裁剪的马赛克

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

var w, h, cnt = 0,

dir = 1,

rd = 0,

deg2rads = Math.PI / 180;

var cv = document.getElementById('cv'),

cv2 = document.getElementById('cv2'),

ctx = cv.getContext('2d'),

ctx2 = cv2.getContext('2d');

var cols = ['#333333', '#000000', '#660000'];

var len = cols.length;

function update() {

var curve = 1000;

rd += dir * (Math.random() * 2);

ctx.fillStyle = cols[cnt % len];

cnt += 1;

ctx.beginPath();

ctx.moveTo(-rd, -rd);

ctx.bezierCurveTo(0, -rd - curve, 0, -rd - curve, +rd, -rd);

ctx.bezierCurveTo(rd + curve, 0, rd + curve, 0, +rd, rd);

ctx.bezierCurveTo(0, rd + curve, 0, rd + curve, -rd, +rd);

ctx.bezierCurveTo(-rd - curve, 0, -rd - curve, 0, -rd, -rd);

ctx.fill();

var rot = (rd * 2) * deg2rads;

ctx.transform(Math.cos(rot), -Math.sin(rot), Math.sin(rot), Math.cos(rot), 0, 0);

ctx2.save();

ctx2.beginPath();

ctx2.arc(w / 2, h / 2, Math.max(rd, 1), 0, 2 * Math.PI, false);

ctx2.clip();

ctx2.drawImage(cv, 0, 0);

ctx2.restore();

//cv2.style.transform = 'rotate('+cnt+'deg)';

if (rd > h / 2) {

rd = 0;

cols[2] = 'rgb(' + (100 + 55 * Math.random() | 0) + ',' + (100 + 55 * Math.random() | 0) + ',' + (100 + 55 * Math.random() | 0) + ')';

}

requestAnimationFrame(update);

}

function resize() {

cv.width = window.innerWidth;

cv.height = window.innerHeight;

cv2.width = window.innerWidth;

cv2.height = window.innerHeight;

w = cv.width;

h = cv.height;

ctx.globalCompositeOperation = 'destination-atop';

ctx.transform(1, 0, 0, 1, w / 2, h / 2);

}

resize();

update();

window.onresize = resize;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用微信小程序的 Canvas 组件和相关 API 来实现图片裁剪圆形的效果。以下是一个简单的示例代码: 1. 在你的小程序页面的 JSON 文件中添加 Canvas 组件: ```json { "usingComponents": { "canvas": "/path/to/canvas" } } ``` 2. 在你的小程序页面的 WXML 文件中添加 Canvas 组件的标签: ```html <canvas canvas-id="myCanvas" style="width: 200px; height: 200px;"></canvas> ``` 3. 在你的小程序页面的 JS 文件中编写相关代码: ```javascript Page({ onReady: function () { const ctx = wx.createCanvasContext('myCanvas') wx.getImageInfo({ src: '/path/to/image.jpg', success: function (res) { const imgWidth = res.width const imgHeight = res.height const radius = imgWidth > imgHeight ? imgHeight / 2 : imgWidth / 2 ctx.save() ctx.beginPath() ctx.arc(radius, radius, radius, 0, 2 * Math.PI) ctx.clip() ctx.drawImage(res.path, 0, 0, imgWidth, imgHeight, 0, 0, radius * 2, radius * 2) ctx.restore() ctx.draw() } }) } }) ``` 上述代码中,通过 `wx.getImageInfo` 方法获取图片信息,然后根据图片大小确定裁剪半径。接下来,在 Canvas 上绘制一个圆形路径并使用 `ctx.clip()` 方法进行裁剪。最后,使用 `ctx.drawImage` 方法将图片绘制在裁剪后的区域内。最后调用 `ctx.draw()` 方法进行渲染。 请注意替换示例代码中的图片路径和 Canvas 组件的样式为你实际使用的路径和样式。 希望对你有所帮助!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值