primitive.js照片变成矢量SVG图片实例页面

回到相关文章 »

效果:

代码:

HTML代码:
<img src="./ps1.jpg" width="500" height="375">
<p><input type="button" id="button" value="点击变身"></p>
<div id="container"></div>
                
JS代码:
<script src="./primitive.js"></script>
<script>
document.getElementById('button').addEventListener('click', function () {
    var Canvas = PRIMITIVE.Canvas;    
    var Optimizer = PRIMITIVE.Optimizer;
    var cfg = {
        alpha: 0.5,
        computeSize: 256,
        fill: "rgb(0, 0, 0)",
        height: 375,
        mutateAlpha: true,
        shapeTypes: [PRIMITIVE.shapeMap.triangle],
        mutations: 30,
        shapes: 200,
        steps: 100,
        viewSize: 500,
        width: 500
    };
    
    function go(original, cfg) {
        let optimizer = new Optimizer(original, cfg);
    
        let cfg2 = Object.assign({}, cfg, {width:cfg.scale*cfg.width, height:cfg.scale*cfg.height});
        let result = Canvas.empty(cfg2, false);
        result.ctx.scale(cfg.scale, cfg.scale);
        document.getElementById('container').appendChild(result.node);

        optimizer.onStep = (step) => {
            if (step) {
                result.drawStep(step);
            }
        };
        optimizer.start();
    }
    
    Canvas.original('./ps1.jpg', cfg).then(original => go(original, cfg));
});
</script>