【问题标题】:Rotate a full size canvas image from a centerpoint without moving other canvas images从中心点旋转全尺寸画布图像而不移动其他画布图像
【发布时间】:2014-08-22 18:20:42
【问题描述】:

下面的代码示例可以在这里查看-http://dev.touch-akl.com/celebtrations/

我一直在尝试做的是在画布上绘制 2 个图像(发光然后耀斑。这些图像的链接如下)

http://dev.touch-akl.com/celebtrations/wp-content/themes/beanstalk/img/flare.jpg

http://dev.touch-akl.com/celebtrations/wp-content/themes/beanstalk/img/blue-background.jpg

目标是让“蓝色背景”图像以容器的高度和宽度放置在画布上,并以混合模式将“耀斑”图像绘制在该图像之上并以动画来创造一种闪烁的效果。

我的问题是,因为我使用的图像是矩形的,所以当“耀斑”在某些点旋转时,您可以看到下面图层的边缘...

我尝试做的是使用三角函数找到容器的对角线宽度,并以该宽度绘制“耀斑”图像,使其始终覆盖整个画布,但遗憾的是,您仍然可以在某些点看到背景层(但是比以前少得多)。

我需要一种方法让耀斑图像始终覆盖整个画布,谁能指出我正确的方向?

  var banner = $('#banner'),
    flare = document.getElementById('flare'),
    glow = document.getElementById('glow'),
    canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    blendMode = "multiply";

$window.load(function(){

    _canvasWidth = banner.outerWidth(),
    _canvasHeight = banner.outerHeight();

    canvas.width = _canvasWidth;
    canvas.height = _canvasHeight;

    var _flareSum = (_canvasWidth * _canvasWidth) + (_canvasHeight * _canvasHeight);
        _flareWidth = Math.sqrt(_flareSum); 

    _angle = 0;

    setInterval(function() {

        _angle = _angle +0.25;

        // draw the bg without a blend mode
        ctx.globalCompositeOperation = "source-over";  
        ctx.drawImage(glow, 0, 0, _canvasWidth, _canvasHeight); 
        ctx.save();

        // clear the canvas
        // ctx.clearRect(0, 0, _canvasWidth, _canvasHeight);

        ctx.translate( _canvasWidth/2, _canvasHeight);  // move to center point

        ctx.globalCompositeOperation = blendMode;
        ctx.rotate(Math.PI / 180 * (_angle)); // 1/2 a degree
        ctx.drawImage(flare, -_flareWidth/2, -_flareWidth/2, _flareWidth, _flareWidth); // redraw ia=mages

        ctx.restore();

        //console.log(_angle)

    }, 1);

【问题讨论】:

  • 请注意,下面的解决方案效果很好,我所做的是获取 minScale 数量,然后将其乘以三角形的宽度!

标签: javascript jquery html animation canvas


【解决方案1】:

如果我理解正确,当耀斑以任意角度旋转时,您需要耀斑的最短部分仍然覆盖画布。

由于您在任何时候只显示一半的耀斑,所以耀斑的最短部分是从耀斑中心到耀斑顶部的距离:

var flareMinHeight = flare.height/2;

光晕必须覆盖的最长长度是从光晕旋转点到画布的左上角。

var dx=rotationPointX;
var dy=rotationPointY;
var requiredLength=Math.sqrt(dx*dx+dy*dy);

所以你需要将耀斑缩放到至少上面计算的长度:

var minScale = requiredLength / flareMinHeight;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 2018-11-25
    • 2015-10-01
    • 2015-02-25
    • 2010-09-26
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多