【问题标题】:Drawing a SVG file on a HTML5 canvas at a specific time在特定时间在 HTML5 画布上绘制 SVG 文件
【发布时间】:2015-10-08 06:59:27
【问题描述】:

我找到了关于渲染 SVG 的主题 Drawing an SVG file on a HTML5 canvas。有没有办法在特定时间绘制 SVG 动画文件?我的意思是,如何更改代码

var img = new Image();
img.onload = function() {
    ctx.drawImage(img, 0, 0); // define time at here: time="1.3sec"
}
img.src = "myfile.svg";

这样img 在特定时间包含 svg? 文件 myfile.svg 包含以下内容:

<svg
   xmlns="http://www.w3.org/2000/svg"
   viewBox="0 0 200 200"
   id="svg2">

    <g transform="translate(100, 100)">
        <path transform="matrix(0.99982594,0.01865711,-0.01865711,0.99982594,0,0)" style="opacity:1;fill:#28b327;fill-opacity:1;stroke:#000000;stroke-width:1.5;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" d="M 23.755845,-0.77020556 A 23.938168,23.938168 0 0 1 -0.1823229,23.167962 23.938168,23.938168 0 0 1 -24.12049,-0.77020556 23.938168,23.938168 0 0 1 -0.1823229,-24.708373 23.938168,23.938168 0 0 1 23.755845,-0.77020556 Z" id="ball-2-path4136">
        <animate to="M 17.577751,-4.4423325 A 17.748762,27.248762 1.0690357 0 1 -0.67630452,22.470547 17.748762,27.248762 1.0690357 0 1 -17.913594,-5.1046137 17.748762,27.248762 1.0690357 0 1 0.3404618,-32.017493 17.748762,27.248762 1.0690357 0 1 17.577751,-4.4423325 Z" dur="0.2" begin="1.4" attributeName="d" fill="freeze"/></path>

    </g>
</svg>

人们通常建议使用canvg,但据我了解它不支持路径动画,所以我的示例不适用于它。

【问题讨论】:

标签: javascript animation canvas svg canvg


【解决方案1】:

您可以简单地使用setTimeout 来延迟插入正方形,以这种方式:

var delayInMilliseconds = 3000;

img.onload = function() {
    setTimeout(function() {
        // This will happend 3 seconds after page load
        ctx.drawImage(img, 0, 0);
    }, delayInMilliseconds);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Svg_example_square.svg";

如果您希望能够为事件指定日期和时间,请使用自定义函数来计算距离目标日期的剩余时间:

function getTimeTo(date) {
    var time = date.getTime() - Date.now();
    return time;
}

并将delayInMilliseconds 替换为getTimeTo(targetDate)。请参阅this fiddle 进行实验。

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2013-01-07
    • 2011-03-11
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多