Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <section>
    <article>
         <canvas id="canvas"></canvas>
    </article>
    <div>
      选择图片,点击Canvas!
      <input type="file" name="getImage" id="getImage">
    </div>
  </section>
</body>
</html>
              
            
!

CSS

              
                
section{
  display:flex
}
section div{
  flex-shrink:1;
}
article{
  flex-shrink:0;
  margin-right:10px;
}
canvas{
  width:500px;
  heigth:500px;
  background:#000;
}
              
            
!

JS

              
                       let allBodies=[];
        let image=null;
        let isStop=true;
        let isloading=false;
        let canvasImage={};
        const input = document.getElementById("getImage")
        const dpr=2
        const canvas=document.getElementById("canvas")
        const context=canvas.getContext("2d")
        const canvasSize=500
        const canvasWidth=canvasSize*dpr
        const canvasHeight=canvasSize*dpr
        const cap=50
        const colNum=Math.ceil(canvasWidth/cap)-1
        const rowNum=Math.ceil(canvasHeight/cap)-1
        const lineWidth=2
        canvas.width=canvasWidth
        canvas.height=canvasHeight

        let balls=[]
        var Engine = Matter.Engine,
                Render = Matter.Render,
                Runner = Matter.Runner,
                Composite = Matter.Composite,
                Composites = Matter.Composites,
                Common = Matter.Common,
                MouseConstraint = Matter.MouseConstraint,
                Mouse = Matter.Mouse,
                World = Matter.World,
                Body = Matter.Body,
                Bodies = Matter.Bodies;
            var engine = Engine.create(),
                world = engine.world;
            var runner = Runner.create();
            var mouse = Mouse.create(canvas);
            var    mouseConstraint = MouseConstraint.create(engine, {
                    mouse: mouse,
                    constraint: {
                        stiffness: 0.2,
                        render: {
                            visible: false
                        }
                    }
                });

            World.add(world, mouseConstraint);
       
        //建立网格
        function createGrid(){
        context.fillStyle = 'green';
        context.textAlign="center"
        context.font="24px Arial"
        context.textBaseline="top"
        for(let i=1;i<=colNum;i++){
            context.fillRect( cap*i-1, 0,lineWidth,colNum*cap)
            context.fillText (i*cap,cap*i-1,colNum*cap+5);   
        }
        context.textAlign="left"
        context.font="24px Arial"
        context.textBaseline="middle"
        for(let i=1;i<=rowNum;i++){
            context.fillRect( 0,cap*i-1,rowNum*cap,lineWidth)
            context.fillText (i*cap,rowNum*cap+5,cap*i-1);
        }
        }
        createGrid()

        input.addEventListener("change",function(e){
            if(isloading) return
            isloading=true;
            for (let i = 0;i < this.files.length;i++){
                destory()
                getImageFormFile(this.files[i],renderImage); 
            }
        })
        function checkType(type){
            var r=false
            switch (type){
                case 'image/jpg':r=true;break;
                case 'image/png':r=true;break;
                case 'image/jpeg':r=true;break;
                case 'image/gif':r=true;break;
            }
            return r;
        }
        function getImageFormFile(file,callback){
            let reader = new FileReader();
            if(checkType(file.type)){
                reader.readAsDataURL(file);
            }
            reader.addEventListener('load',function () {
                if(checkType(file.type)){
                    let img = new Image();
                    img.src = reader.result;
                    img.onload=function(){
                        image=img
                        callback();
                    }
                    
                }
            });
        }
        function initImage(){
            context.clearRect(0,0,canvas.width,canvas.height);
            createGrid()
        }
        function renderImage(){
            isloading=false
            function createAnimate(){
                canvas.removeEventListener("click",createAnimate)
                getImageData()
                play()
            }
            initImage()
            let  scale=image.width/image.height;
            let size=canvasSize*1.5
            canvasImage.width = scale>1?size:size*scale
            canvasImage.height = canvasImage.width/scale
            canvasImage.x = canvasSize-canvasImage.width/2
            canvasImage.y = canvasSize-canvasImage.height/2
            context.drawImage(image, canvasImage.x,canvasImage.y,canvasImage.width,canvasImage.height);
            canvas.addEventListener("click",createAnimate)
        }
        function drawCircle(ball){
            context.fillStyle =ball.render.fillStyle;  
            context.beginPath();
            if(ball.label==="Rectangle Body"){
                //context.fillStyle ="red";
                //context.rect(ball.bounds.min.x, ball.bounds.min.y, ball.bounds.max.x - ball.bounds.min.x, ball.bounds.max.y - ball.bounds.min.y);          context.fill();  
            }else{
                context.arc (ball.position.x,ball.position.y,ball.circleRadius,0,2*Math.PI); 
                context.fill();  
            }
            context.closePath();
        
        
        }
        function getImageData(){
            let data= context.getImageData(canvasImage.x,canvasImage.y,canvasImage.width,canvasImage.height);
            initImage()
            let cap=15;
            let bound={x:data.width,y:data.height};
            let initPos={x:cap,y:cap}
            let x=initPos.x,y=initPos.y
            let friction=0.001;
            do{
                
                do{
                    let random=Common.random();
                    let pointIndex=data.width*y+x
                    let num=pointIndex*4;
                    let ball=Bodies.circle(canvasImage.x+x,canvasImage.y+y,cap, { 
                        frictionAir: friction, 
                        restitution: 1,
                        render:{fillStyle:"rgba("+data.data[num]+","+data.data[num+1]+","+data.data[num+2]+","+data.data[num+3]+")" } 
                    });
                    Body.setVelocity(ball, { x: Math.pow(-1,Math.round((random*10))), y: Math.pow(-1,Math.round((random*10)))*10});
                    balls.push(ball)
                    x+=cap*2;
                }while(x<=bound.x)
                x=initPos.x
                friction += 0.001
                y+=cap*2
            }while(y<=bound.y)
            
        World.add(world, [
            ...balls,
            // Bodies.rectangle(canvasWidth/2, 0, canvasWidth, 50, { isStatic: true }),
            // Bodies.rectangle(0, canvasHeight/2, 50, canvasHeight,{ isStatic: true }),
            // Bodies.rectangle(canvasWidth, canvasHeight/2, 50, canvasHeight, { isStatic: true }),
            // Bodies.rectangle(canvasWidth/2, canvasHeight,  canvasWidth, 50, { isStatic: true })
        ]);

        allBodies = Composite.allBodies(world);

        for (var i = 0; i < allBodies.length; i += 1) {
            allBodies[i].plugin.wrap = {
                min: { x: 0, y: 0 },
                max: { x: canvasWidth, y: canvasHeight }
            };
        }
        }
        function animation(){
            initImage()
            allBodies.forEach((ball)=>{
                drawCircle(ball)
            })
            if(isStop) return
            window.requestAnimationFrame(()=>{
                animation()
            })
        }
        function play(){
            isStop=false
            Runner.run(runner, engine);
            animation()
        }
        function destory(){
            isStop=true
            Matter.Runner.stop(runner);
            World.remove(engine.world, Composite.allBodies(world));
            initImage()
            allBodies=[]
            balls=[]
        }
              
            
!
999px

Console